#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: api_for_publish.py 
@version:
@time: 2022/05/07 
"""
from TapClientCore.T02_tm_api.v2_api.v2_api_module.api13_oauth import Api13Oauth
from TapClientCore.T02_tm_api.v2_api.v2_api_module.api14_application import Api14Application
from TapUtil.decorator.some_useful import func_logger


class ApplicationForRequests(Api13Oauth, Api14Application):

    # 返回token
    @property
    def token(self):
        payload = self.get_application_info_for_token()
        return self.get_oauth_token(payload)

    # —— 返回token需要的info
    @staticmethod
    def _get_application_by_filter(_filter):
        data_list = Api14Application().get_application_by_filter(_filter).get('data').get('items')
        for one in data_list:
            if one.get('scopes') == ['admin']:
                return one

    # 返回token需要的info
    def get_application_info_for_token(self):
        _filter = {"order": "clientName DESC", "limit": 20, "skip": 0, "where": {}}
        response = self._get_application_by_filter(_filter)
        clientSecret = response.get('clientSecret')
        client_id = response.get('id')
        return {
            'grant_type': 'client_credentials',
            'client_id': client_id,
            'client_secret': clientSecret
        }


from TapClientCore.T02_tm_api.v2_api.v2_api_base import V2ApiUrlBase, api_joint


# api url generate
class APIForPublishUrl(V2ApiUrlBase):
    url_base = api_joint(V2ApiUrlBase().apiserver, 'v1')
    token = ApplicationForRequests().token


# api use
class APIForPublish(ApplicationForRequests):
    api_token = f'?access_token={APIForPublishUrl.token}'
    api_token2 = f'&access_token={APIForPublishUrl.token}'

    # 新增 post
    @func_logger
    def post_insert_record(self, path, data):
        response = self.tapclient(
            self.post,
            api_joint(
                APIForPublishUrl.url_base,
                path
            )
            + self.api_token,
            json=data
        )
        return response

    # 删除 get by pk
    @func_logger
    def get_delete_by_id(self, path, pk):
        response = self.tapclient(
            self.get,
            api_joint(
                APIForPublishUrl.url_base,
                path,
                str(pk),
                'delete'
            )
            + self.api_token,
        )
        return response

    # 删除 delete by pk
    @func_logger
    def delete_delete_by_id(self, path, pk):
        response = self.tapclient(
            self.delete,
            api_joint(
                APIForPublishUrl.url_base,
                path,
                str(pk)
            )
            + self.api_token,
        )
        return response

    # 删除 delete by where
    @func_logger
    def delete_delete_by_where(self, path, where):
        """
        ?where[pk]=2&where[title]=title
        """
        str_list = [f'where[{k}]={v}' for k, v in where.items()]
        print(str_list)
        response = self.tapclient(
            self.delete,
            api_joint(
                APIForPublishUrl.url_base,
                path,
            )
            + f'?{api_joint(*str_list, division="&")}'
            + self.api_token2,
        )
        return response

    # 更新 post by pk , payload
    @func_logger
    def post_update_by_id(self, path, pk, payload):
        response = self.tapclient(
            self.post,
            api_joint(
                APIForPublishUrl.url_base,
                path,
                str(pk)
            )
            + f'?access_token={APIForPublishUrl.token}',
            json=payload
        )
        return response

    # 更新 patch by pk , payload
    @func_logger
    def patch_update_by_id(self, path, pk, payload):
        response = self.tapclient(
            self.patch,
            api_joint(
                APIForPublishUrl.url_base,
                path,
                str(pk)
            )
            + f'?access_token={APIForPublishUrl.token}',
            json=payload
        )
        return response

    # 更新 patch by where
    @func_logger
    def patch_update_by_where(self, path, where, payload):
        """
        ?where[pk]=2&where[title]=title
        """
        str_list = [f'where[{k}]={v}' for k, v in where.items()]
        print(str_list)
        response = self.tapclient(
            self.patch,
            api_joint(
                APIForPublishUrl.url_base,
                path,
            )
            + f'?{api_joint(*str_list, division="&")}'
            + self.api_token2,
            json=payload
        )
        return response

    # count
    @func_logger
    def get_count(self, path):
        response = self.tapclient(
            self.get,
            api_joint(
                APIForPublishUrl.url_base,
                path,
                'count'
            )
            + self.api_token,
        )
        print(self.api_token)
        return response

    # 查询 post by payload= {}
    @func_logger
    def post_find_by_page(self, path, payload=None):
        if payload is None:
            payload = {}
        response = self.tapclient(
            self.post,
            api_joint(
                APIForPublishUrl.url_base,
                path,
                'find'
            )
            + self.api_token,
            json=payload
        )
        return response

    # 查询 get by pk
    @func_logger
    def get_query_by_id(self, path, pk):
        response = self.tapclient(
            self.get,
            api_joint(
                APIForPublishUrl.url_base,
                path,
                str(pk)
            )
            + self.api_token,
        )
        return response

    # 查询 get by  _filter
    @func_logger
    def get_query_by_page(self, path, _filter):
        if _filter is None:
            _filter = '?filter[offset]=0&filter[limit]=100&filter[skip]=0'
        response = self.tapclient(
            self.get,
            api_joint(
                APIForPublishUrl.url_base,
                path,
            )
            + _filter

            + self.api_token2,
        )
        return response


if __name__ == '__main__':
    T = APIForPublish()
    _path = 'docker_mysql_5733_B_MYSQL1650879539472176053'
    data = {
        "pk": 2,
        "title": "title"
    }
    print(T.get_count(_path))
